<script setup lang="ts">
/*
 computed
  1:导入
  2:  const 变量名=computed<number>(()=>{
    return 值
  })
  3：访问： 
      js:变量名.value
      html:变量名 
*/

import { computed } from '@vue/reactivity'
import { ref } from 'vue'
import CartList from './components/CartList.vue'

const list = ref<
  {
    id: number
    name: string
    num: number
    price: number
  }[]
>([
  { id: 1, name: '白菜', num: 1, price: 3 },
  { id: 2, name: '西红柿', num: 3, price: 4 }
])

const totalPrice = computed<number>(() => {
  return list.value.reduce((pre, item) => {
    return pre + item.num * item.price
  }, 0)
})

// 修改数据
const setNum = (id: number, step: number) => {
  const findItem = list.value.find(item => item.id === id)
  if (findItem) {
    findItem.num += step
    if (findItem.num < 0) {
      findItem.num = 0
    }
  }
}
</script>

<template>
  <div class="app-page">
    <div class="item">
      <div class="name">商品名</div>
      <div class="num">数量</div>
      <div class="price">价格</div>
    </div>
    <CartList :list="list" @setNum="setNum"></CartList>
    <div class="total">总价:{{ totalPrice }}</div>
  </div>
</template>

<style lang="scss" scoped>
.app-page {
  width: 500px;
  border: 5px solid #ccc;
  .item {
    display: flex;
    justify-content: space-evenly;
    div {
      flex: 1;
      text-align: center;
    }
  }
  .total {
    text-align: right;
  }
}
</style>
